package main

import (
	"golang-master/photo-gallery/config"
	"golang-master/photo-gallery/handlers"
	"golang-master/photo-gallery/middleware"
	"golang-master/photo-gallery/models"
	"golang-master/photo-gallery/utils"
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func initDB(db *gorm.DB) {
	// 创建表
	db.AutoMigrate(&models.User{}, &models.Image{}, &models.Category{}, &models.Tag{})
}

func setupRouter(db *gorm.DB) *gin.Engine {
	// 初始化会话存储
	utils.InitSession()

	r := gin.Default()
	// 应用会话中间件到所有路由
	r.Use(utils.SessionMiddleware())

	auth := handlers.NewAuthHandler(db)
	imageHandler := handlers.NewImageHandler(db)
	categoryTagHandler := handlers.NewCategoryTagHandler(db)

	//公开路由
	authGroup := r.Group("/v1")
	{
		authGroup.POST("/register", auth.Register)
		authGroup.POST("/login", auth.Login)
		authGroup.POST("/logout", auth.Logout)
	}

	// 受保护的路由
	protected := r.Group("/")
	protected.Use(middleware.AuthMiddleware())
	{
		// 图片管理
		protected.POST("/images/upload", imageHandler.UploadImage)
		protected.GET("/images", imageHandler.GetImages)
		protected.DELETE("/images/:id", imageHandler.DeleteImage)
		// 分类管理
		protected.POST("/categories", categoryTagHandler.CreateCategory)
		protected.GET("/categories", categoryTagHandler.GetCategories)
		protected.DELETE("/categories/:id", categoryTagHandler.DeleteCategory)

		// 标签管理
		protected.POST("/tags", categoryTagHandler.CreateTag)
		protected.GET("/tags", categoryTagHandler.GetTags)
		protected.DELETE("/tags/:id", categoryTagHandler.DeleteTag)

	}

	return r
}

func main() {
	// 连接数据库
	config.ConnectDatabase()

	// 初始化数据表
	initDB(config.DB)

	// 设置路由
	r := setupRouter(config.DB)

	// 启动服务器
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	/*r.GET("/gin", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello, Gin!"})
	})*/

	log.Printf("Server starting on port %s", port)
	r.Run(":" + port)
}
